package com.quick.develop.form.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.quick.develop.business.enums.BusinessEnums;
import com.quick.develop.form.process.BusinessScanProcess;
import com.quick.develop.framework.common.exception.ServerException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

public class FormUtils {

    public static Object handleFormServiceMethodType(String beanName, Class<?> type, Map<String, Object> params) throws InvocationTargetException, IllegalAccessException {
        Object bean = getFormServiceElseThrow(beanName);
        Method targetMethod = getTargetMethods(beanName, type);
        if (Objects.isNull(targetMethod)) {
            throw new ServerException("未定义处理方法！");
        }
        Class<?> parameterType = targetMethod.getParameterTypes()[0];
        Object targetParams;
        try {
            targetParams = BeanUtil.toBean(params, parameterType);
        } catch (Exception e) {
            throw new ServerException("解析参数异常：" + e.getMessage());
        }
        return targetMethod.invoke(bean, targetParams);
    }

    public static Object handleFormServiceMethodType(String beanName, Class<?> type, Object params) throws InvocationTargetException, IllegalAccessException {
        Object bean = getFormServiceElseThrow(beanName);
        Method targetMethod = getTargetMethods(beanName, type);
        if (Objects.isNull(targetMethod)) {
            throw new ServerException("未定义处理方法！");
        }
        return targetMethod.invoke(bean, params);
    }

    public static Object getFormServiceElseThrow(String businessType) {
        String beanName = BusinessEnums.getDefinitionBeanName(businessType);
        return Optional.ofNullable(SpringUtil.getBean(beanName))
                .orElseThrow(() -> new ServerException("未找到表单服务类:" + beanName));
    }

    public static Method getTargetMethods(String beanName, Class<?> type) {
        return BusinessScanProcess.definitionMethods.get(parserBusinessFormKey(beanName, type.getName()));
    }

    public static String parserBusinessFormKey(String beanName, String annotationName) {
        return beanName + "#" + annotationName;
    }
}
